var express = require('express');
var router = express.Router();

var BufferHelper = require('bufferhelper');
var request = require('request');
var jRequest = request.defaults({jar: true, maxRedirects: 30});
var querystring = require('querystring');
var cheerio = require('cheerio');
var iconv = require('iconv-lite');
var url = require('url');
var util = require('util');
var async = require('async');
var fs = require('fs');

var crawlerStudent = require('../utils/crawlerStudent');
var loginInfo;
/*
* "schoolname" : "杭州师范大学",
 "entryurl" : "http://jwgl1.hznu.edu.cn/",
 "txtusername" : "txtUserName",
 "txtpassword" : "TextBox2",
 "txtsecretcode" : "txtSecretCode",
 "__v" : NumberInt("0"),
 "schoolcode" : "10346",
 "schoolid" : NumberInt("890")*/



var entryUrl = "http://jwgl1.hznu.edu.cn/";

/* GET home page. */
router.post('/', function (req, res, next) {
    res.send("sss" );
    // res.render('index', {title: 'Express'});
});


router.post('/getCheckCode', function (req, ress, next) {
    jRequest({
        url: entryUrl + 'default2.aspx'
    }, function (err, res, body) {//首页请求
        if (err) {
            return console.error(err)
        }
        var $ = cheerio.load(body);
        var eventTarget = $('input[name=__EVENTTARGET]').attr('value');
        var eventArgument = $('input[name=__EVENTARGUMENT]').attr('value');
        var viewState = $('input[name=__VIEWSTATE]').attr('value');

        var cookie = res.client._httpMessage.path.toString();
        cookie = cookie.match(/\([a-z,A-Z,0-9]*\)/);
        if (cookie != null) {
            cookie = cookie[0] + '/';
        } else {
            cookie = ""
        }
        var loginUrl = url.resolve(entryUrl, cookie + 'default2.aspx');
        loginInfo = {
            cookie: cookie,
            eventTarget: eventTarget,
            eventArgument: eventArgument,
            viewState: viewState,
            loginUrl: loginUrl,
            entryUrl: entryUrl,
            txtusername: "txtUserName",
            txtpassword: "TextBox2",
            txtsecretcode: "txtSecretCode"
        }


        var codeBuffer = new BufferHelper();
        jRequest.get({
                url: entryUrl + cookie + 'CheckCode.aspx',
                //Referer:entryUrl,
                followAllRedirects: true
            }
        )//获取验证码
            .on('error', function (err) {
                console.log(err);
            })
            .on('data', function (chunck) {
                codeBuffer.concat(chunck);
            })
            .on('end', function () {
                var con = codeBuffer.toBuffer();
                fs.writeFileSync('code.jpg', con);
                // console.log(con);
                ress.send(con);
            });
    });
});
router.post("/test",function (req, res, next) {
    // var loginInfo = req.body.loginInfo;
    var username = req.body.username;
    var password = req.body.password;
    var checkCode = req.body.checkCode;

    if (username == "2014210950" && password == "mxh123456"){
        res.send("success!");
    }else{
        res.send("error");
    }

})

router.post("/loginAndGetCourses",function (req, res, next) {
    // var loginInfo = req.body.loginInfo;
    var username = req.body.username;
    var password = req.body.password;
    var checkCode = req.body.checkCode;
    // username = "2014210950";
    // password = "mxh123456";

    crawlerStudent.loginFetchData(username, password, loginInfo.cookie, checkCode, loginInfo.viewState, loginInfo.loginUrl, loginInfo.entryUrl, loginInfo.txtusername, loginInfo.txtpassword, loginInfo.txtsecretcode, function (err, result) {
        if (err) {
            res.send(err);
        } else {
            console.log(result);
            res.send(result);
        }
    });

})


module.exports = router;
